package com.hc;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Before;
import org.junit.Test;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MybatisOperater {
    /** mybatis开发步骤
     * 1.导入依赖
     * 2.编写核心配置文件
     * 3.创建Bean
     * 4.编写对应Mapper
     * 5.操作数据库
     */
    SqlSession sqlSession;
    BeanMapper beanMapper;
    @Before
    public void init() throws IOException {
        //5.------------->
        //1.读取mybatis核心配置文件
        InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
        //2.获取会话工厂，读取数据源等信息
        SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(inputStream);
        //3.创建会话
        sqlSession = factory.openSession();
        //4.获取接口对象进行后续操作(该对象将sql语句封装成方法用以调用，调用对象中的方法即相当于执行sql)
        beanMapper = sqlSession.getMapper(BeanMapper.class);
    }

    @Test
    public void fun1() {
        //4.直接开始进行数据库操作，com.hc.UserMapper对应namespace的值
        List<User> userList = sqlSession.selectList("com.hc.UserMapper.selectAllUser");
        for (User u:userList) {
            System.out.println(u);
        }
    }

    @Test
    public void fun2() {
        User user = new User();
        user.setUsername("王五");
        user.setPassword("666");
        user.setPhone("112233");
        user.setAge(18);
        user.setGender(1);
        int i = sqlSession.insert("com.hc.UserMapper.insertUser", user);
        sqlSession.commit();
        System.out.println("i:" + i);
    }

    @Test
    public void fun3() {
        User user = new User();
        user.setUsername("赵六");
        user.setPassword("666");
        user.setPhone("112233");
        int i = sqlSession.insert("com.hc.UserMapper.insertUser2", user);
        sqlSession.commit();
        System.out.println("i:" + i);
    }

    @Test
    public void fun4(){
        Integer[] array = {5,9};
        int i = sqlSession.delete("com.hc.UserMapper.deleteUserById", array);
        sqlSession.commit();
        System.out.println("i:" + i);
    }

    @Test
    public void fun5(){
        //使用Map集合传递数据时，key必须和#{}占位符中的名称保持一致
        Map<String,Integer> map = new HashMap<>();
        map.put("minAge",20);
        map.put("maxAge",22);
        List<User> userList = sqlSession.selectList("com.hc.UserMapper.selectUserByAge",map);
        for(User user:userList){
            System.out.println(user);
        }
    }

    @Test
    public void fun6(){
        User user = beanMapper.selectUserById(4);
        System.out.println(user);
    }

    @Test
    public void fun7(){
        List<Teacher> teacherList = beanMapper.selectAllTeacherWithStudent();
        for(Teacher teacher:teacherList){
            System.out.println(teacher);
        }
    }
}
